<template>
  <div>
    <rj-table
      :columns="authDeviceColumns"
      :data-source="authDevices"
      :pagination="pagination"
      :loading="loading"
      @change="onChangeTable"
      rowKey="id"
      :row-selection="{
        onChange: onSelectChange,
      }"
    >
      <div slot="customBlock" class="log-opt-wrapper">
        <a-space :size="16">
          <a-button class="add-btn" type="primary" @click="onAddDevice">
            <icon-font type="ic-plus" />
            {{ $t('authDevice.addDev') }}
          </a-button>
          <!-- <a-button style="display: none"> 导入 </a-button> -->
          <a-button @click="onBatchDelete()">
            {{ $t('common.batchDelete') }}
          </a-button>
          <a style="display: none">{{ $t('authDevice.devGuide') }}</a>
        </a-space>
        <a-space :size="16">
          <a-select
            v-model="deviceGroupId"
            @change="getAuthDeviceList"
            style="width: 200px"
          >
            <icon-font type="ic-tree-device" slot="menuItemSelectedIcon" />
            <!-- <div slot="dropdownRender" slot-scope="menu">
              <v-nodes :vnodes="menu" />
              <a
                style="padding: 4px 8px 8px; cursor: pointer; display: block"
                @mousedown="(e) => e.preventDefault()"
                @click="onAdd"
              >
                <icon-font type="ic-plus" />
                {{ $t('authDevice.addGroup') }}
              </a>
            </div> -->
            <a-select-option
              v-for="item in authDeviceGroups"
              :key="item.id"
              :title="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-input-search
            :placeholder="$t('authDevice.ipNameSn')"
            v-model="queryParamObj.devIpAndName"
            @change="onChangeSearch"
            style="width: 200px"
          />
        </a-space>
      </div>
      <template slot="timeColumn" slot-scope="text">
        {{ formatDate(text) }}
      </template>
      <template slot="deviceGroup" slot-scope="text">
        {{ getAuthDeviceGroupName(text) }}
      </template>
      <!-- 认证类型 -->
      <template slot="modelType" slot-scope="text">
        {{ getModelTypeTxt(text) }}
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <rj-space :size="16">
          <icon-font
            type="ic-edit"
            @click="onEdit(record)"
            :title="$t('common.edit')"
          ></icon-font>
          <icon-font
            type="ic-delete"
            @click="onDelete(record)"
            :title="$t('common.delete')"
          ></icon-font>
        </rj-space>
      </template>
    </rj-table>
    <AddModal
      :deviceGroupId="deviceGroupId"
      @addDeviceGroup="onAddDeviceGroup"
      @refreshList="getAuthDeviceList"
      ref="authDeviceModalRef"
    />
    <AddGroupModal @refreshList="addGroupCallback" ref="addGroupModalRef" />
  </div>
</template>

<script>
import { maccApi, requestHttp } from '@utils/index';
import { mapState } from 'vuex';
import { RjTable } from '@components';
import AddModal from './addModal.vue';
import AddGroupModal from '../authDeviceGroupList/addModal.vue';
import { authDeviceColumns } from './columns.js';
import lodash from 'lodash';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import moment from 'moment-timezone';
export default {
  name: 'AuthDeviceList',
  mixins: [authSysMixin],
  data() {
    return {
      loading: false,
      authDeviceColumns,
      authDevices: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      queryParamObj: {
        devIpAndName: '',
      },
      selectedRowKeys: [],
      deviceGroupId: 0,
      authDeviceGroups: [
        {
          id: 0,
          name: this.$t('common.all'),
        },
      ],
    };
  },
  async mounted() {
    await this.getAuthDeviceGroupList();
    this.getAuthDeviceList();

    this.$EventBus.$on('authDevice/refreshGroupList', () => {
      this.deviceGroupId = 0;
      this.getAuthDeviceGroupList();
      this.getAuthDeviceList();
    });
  },

  destroyed() {
    this.$EventBus.$off('authDevice/refreshGroupList');
  },

  components: {
    'rj-table': RjTable,
    AddModal,
    AddGroupModal,
    // VNodes: {
    //   functional: true,
    //   render: (h, ctx) => ctx.props.vnodes,
    // },
  },
  computed: {
    ...mapState('AuthCommon', ['deviceTypes']),
    authDeviceTypeMap() {
      const tempMap = {};
      for (const deviceType of this.deviceTypes) {
        tempMap[deviceType.key] = deviceType.value;
      }
      return tempMap;
    },
    authDeviceGroupMap() {
      const tempMap = {};
      for (const group of this.authDeviceGroups) {
        tempMap[group.id] = group.name;
      }
      return tempMap;
    },
  },
  methods: {
    formatDate(updateTime) {
      return updateTime ? moment(updateTime).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    async addGroupCallback() {
      await this.getAuthDeviceGroupList();

      if (this.authDeviceGroups.length > 2) {
        this.$refs.authDeviceModalRef.setGroupId(this.authDeviceGroups[1].id);
      }
    },
    getAuthDeviceGroupName(value) {
      const groupName = this.authDeviceGroupMap[value];
      return groupName ? groupName : '';
    },
    getModelTypeTxt(value) {
      return this.authDeviceTypeMap[value] || '';
    },
    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    onAdd() {
      this.$emit('gotoDevGrp');
    },
    onChangeSearch() {
      this.getListDebounce();
    },
    onEdit(record) {
      this.$refs.authDeviceModalRef.openModal(record);
    },
    onAddDevice() {
      this.$refs.authDeviceModalRef.openModal();
    },
    onAddDeviceGroup() {
      this.$refs.addGroupModalRef.openModal();
    },
    onBatchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning(this.$t('common.oneData'));
        return;
      }
      const self = this;
      this.$confirm({
        title: this.$t('common.batchDelete'),
        content: this.$t('authDevice.deleteDevConfirm'),
        onOk() {
          self.deleteDevice(self.selectedRowKeys.join(','));
        },
      });
    },

    onDelete(record) {
      const self = this;
      this.$confirm({
        title: this.$t('common.delete'),
        content: this.$t('authDevice.deleteDevConfirm2'),
        onOk() {
          self.deleteDevice(record.id);
        },
      });
    },

    async deleteDevice(devIdStr) {
      const res = await this.requestHttpAuth({
        api: maccApi.PRIVATE_DEVICE_BATCH_DEL_API,
        method: 'DELETE',
        querys: {
          ids: devIdStr,
        },
      });

      if (res.data.success) {
        this.getAuthDeviceList();
      } else {
        this.$message.warning(res.data.message);
      }
    },

    getListDebounce: lodash.debounce(function () {
      this.getAuthDeviceList();
    }, 500),

    async getAuthDeviceGroupList() {
      const res = await this.requestHttpAuth({
        api: maccApi.PRIVATE_DEVICE_GROUP_GET_API,
        method: 'GET',
        querys: {
          groupId: this.groupId,
          page: 1,
          size: 100,
        },
      });

      if (res.data.success) {
        this.authDeviceGroups = [
          {
            id: 0,
            name: this.$t('common.all'),
          },
        ];
        this.authDeviceGroups = [
          ...this.authDeviceGroups,
          ...res.data.result.items,
        ];
        this.$store.commit(
          'AuthCommon/SET_DEVICE_GROUP_LIST',
          res.data.result.items
        );
      } else {
        this.$message.warning(res.data.message);
      }
    },

    async getAuthDeviceList() {
      const querys = {
        groupId: this.groupId,
        page: this.pagination.current,
        size: this.pagination.pageSize,
        deviceName: this.queryParamObj.devIpAndName,
      };
      if (this.deviceGroupId) {
        querys.areaId = this.deviceGroupId;
      }
      const res = await this.requestHttpAuth({
        api: maccApi.PRIVATE_DEVICE_GET_API,
        method: 'GET',
        querys,
      });

      if (res.data.success) {
        this.pagination.total = res.data.result.total;
        this.authDevices = res.data.result.items;
      } else {
        this.$message.warning(res.data.message);
      }
    },

    //table表格分页变化时触发
    onChangeTable(pagination, filterObj, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getAuthDeviceList();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.defultWapper {
  margin-left: 0;
}

.log-tip {
  font-size: 12px;
  color: #00000073;
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.add-btn {
  i {
    font-size: 15px;
    padding-top: 3px;
  }
}
.binded-dev {
  display: flex;
  align-items: center;
  gap: 8px;
  i {
    font-size: 16px;
    color: @theme-color;
  }
}
</style>
